package com.douqu.game.activity.server.rmi;

import com.douqu.game.activity.GameServer;
import com.douqu.game.activity.entity.BattleServerInfo;
import com.douqu.game.activity.entity.MainServerInfo;
import com.douqu.game.activity.entity.camp.CampPlayer;
import com.douqu.game.activity.entity.camp.StartCampBattleParam;
import com.douqu.game.activity.entity.e.E_PlayerStatus;
import com.douqu.game.activity.manager.ActivityCampManager;
import com.douqu.game.core.config.activity.CampRobotConfig;
import com.douqu.game.core.e.E_ApplyCampActivityType;
import com.douqu.game.core.e.E_BattleDetailType;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.activity.DirectEndData;
import com.douqu.game.core.entity.activity.MatchBaseInfo;
import com.douqu.game.core.entity.battle.*;
import com.douqu.game.core.entity.common.TwoTuple;
import com.douqu.game.core.entity.world.map.ErrorEndParam;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.i.IMainServer;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.LogUtils;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2018-03-09 16:23
 */
public class ActivityServerImpl extends UnicastRemoteObject implements IMainServer
{
    protected ActivityServerImpl() throws RemoteException {
    }

    @Override
    public void battleInit(int battleServerId, String battleId) throws RemoteException
    {
        LogUtils.info("战斗服务器已经收到主服务器发过去的初始化消息--->现在通知客户端去连接战斗服务器 -> " + battleId);

        BattleServerInfo serverInfo = GameServer.getInstance().getBattleServerInfo(battleServerId);
        if (serverInfo != null)
        {
            StartCampBattleParam startBattleParam = serverInfo.getStartBattleParam(battleId);
            if(startBattleParam != null)
            {
                LogUtils.info("开始发送战斗服务器数据------------------>" + battleId);

                startBattleParam.sendStartBattle();

                serverInfo.removeStartBattleParam(battleId);
            }
            else
            {
                LogUtils.error("startBattleParam 为空了 -> " + battleId);
            }
        }
        else
        {
            LogUtils.error("ServerInfo 为空 -> " + battleServerId);
        }
    }

    @Override
    public void battleStart(BattleDetail battleInfo) throws RemoteException
    {
        ActivityCampManager activityManager = GameServer.getInstance().getActivityCampManager();

        try {
            CampPlayer player1 = activityManager.getPlayer(battleInfo.getTeam1Info().getIndexInfo());
            LogUtils.info("player1 -> " + player1);
            if(player1 != null)
            {
                MainServerInfo mainServerInfo1 = GameServer.getInstance().getMainServerInfo(player1.getPlayerBase().getServerId());
                LogUtils.info("mainServerInfo1 -> " + mainServerInfo1);
                if(mainServerInfo1 != null && mainServerInfo1.getRmiServer() != null)
                {
                    LogUtils.info("通知游戏主服战斗开始了->" + player1.getPlayerBase().getName() + " 服务器ID->" + player1.getPlayerBase().getServerId());
                    mainServerInfo1.getRmiServer().campBattleStart(battleInfo.getBattleType(), battleInfo.getTeam1Info().getIndexInfo(), ConstantFactory.BATTLE_TEAM_1);
                    player1.setPlayerStatus(E_PlayerStatus.BATTLE_ING, DataFactory.currentTime);
                }
            }

            if(battleInfo.getBattleDetailType() == E_BattleDetailType.PVP_SPAN_CAMP.getCode())
            {
                CampPlayer player2 = activityManager.getPlayer(battleInfo.getTeam2Info().getIndexInfo());
                LogUtils.info("player2 -> " + player2);
                if(player2 != null)
                {
                    MainServerInfo mainServerInfo2 = GameServer.getInstance().getMainServerInfo(player2.getPlayerBase().getServerId());
                    LogUtils.info("mainServerInfo2 -> " + mainServerInfo2);
                    if(mainServerInfo2 != null && mainServerInfo2.getRmiServer() != null)
                    {
                        LogUtils.info("通知游戏主服战斗开始了->" + player2.getPlayerBase().getName() + " 服务器ID->" + player2.getPlayerBase().getServerId());
                        mainServerInfo2.getRmiServer().campBattleStart(battleInfo.getBattleType(), battleInfo.getTeam2Info().getIndexInfo(), ConstantFactory.BATTLE_TEAM_2);
                        player2.setPlayerStatus(E_PlayerStatus.BATTLE_ING, DataFactory.currentTime);
                    }
                }
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void campBattleStart(int battleType, String playerIndex, int teamNo) throws RemoteException {
        //这里不需要处理
    }

    @Override
    public BattleResultParam battleEnd(BattleDetail battleDetail) throws RemoteException
    {
        LogUtils.info("跨服阵营战斗结束------------" + battleDetail);
        ActivityCampManager activityManager = GameServer.getInstance().getActivityCampManager();
        BattleResultParamCamp battleResult = new BattleResultParamCamp();
        try {
            if(battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_DATA_SPAN_CAMP.getCode()
                    || battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_SPAN_CAMP.getCode())
            {
                BattleResultParamCampSingle winResult = null, loseResult = null;
                MainServerInfo winServer = null, loseServer = null;
                CampPlayer winPlayer = null, losePlayer = null;
                BattleTemp winBattleTemp = null, loseBattleTemp = null;
                if(battleDetail.getWinTeam() == ConstantFactory.BATTLE_TEAM_1)
                {
                    winPlayer = activityManager.getPlayer(battleDetail.getTeam1Info().getIndexInfo());
                    winBattleTemp = battleDetail.getTeam1Info();
                    if(battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_SPAN_CAMP.getCode() || battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_DATA_SPAN_CAMP.getCode())
                    {
                        losePlayer = activityManager.getPlayer(battleDetail.getTeam2Info().getIndexInfo());
                        loseBattleTemp = battleDetail.getTeam2Info();
                    }
                }
                else
                {
                    winPlayer = activityManager.getPlayer(battleDetail.getTeam2Info().getIndexInfo());
                    winBattleTemp = battleDetail.getTeam2Info();
                    if(battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_SPAN_CAMP.getCode() || battleDetail.getBattleDetailType() == E_BattleDetailType.PVP_DATA_SPAN_CAMP.getCode())
                    {
                        losePlayer = activityManager.getPlayer(battleDetail.getTeam1Info().getIndexInfo());
                        loseBattleTemp = battleDetail.getTeam1Info();
                    }
                }

                if(winPlayer != null)
                {
                    winServer = GameServer.getInstance().getMainServerInfo(winPlayer.getPlayerBase().getServerId());
                }
                if(losePlayer != null)
                {
                    loseServer = GameServer.getInstance().getMainServerInfo(losePlayer.getPlayerBase().getServerId());
                }

                if(winServer != null && winServer.getRmiServer() != null)
                {
                    LogUtils.info("战斗结束，通知胜利方玩家的主服 -> winPlayer:" + winPlayer + ", winServer:" + winServer);
                    winResult = winServer.getRmiServer().campBattleEnd(battleDetail.getBattleDetailType(), true, winBattleTemp, losePlayer.getPlayerBase(), null);
                    LogUtils.info("winResult -> " + winResult);
                    GameServer.getInstance().getActivityCampManager().campBattleResult(winPlayer, winResult, battleResult, E_ApplyCampActivityType.BATTLE_END);
                }
                if(loseServer != null && loseServer.getRmiServer() != null)
                {
                    LogUtils.info("战斗结束，通知失败方玩家的主服 -> losePlayer:" + losePlayer + ", loseServer:" + loseServer);
                    loseResult = loseServer.getRmiServer().campBattleEnd(battleDetail.getBattleDetailType(), false, loseBattleTemp, winPlayer.getPlayerBase(), null);
                    LogUtils.info("loseResult -> " + loseResult);
                    GameServer.getInstance().getActivityCampManager().campBattleResult(losePlayer, loseResult, battleResult, E_ApplyCampActivityType.BATTLE_END);
                }
            }
            else
            {
                CampPlayer campPlayer = activityManager.getPlayer(battleDetail.getTeam1Info().getIndexInfo());
                if(campPlayer != null)
                {
                    MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(campPlayer.getPlayerBase().getServerId());
                    if(mainServerInfo != null && mainServerInfo.getRmiServer() != null)
                    {
                        BattleResultParamCampSingle singleResult = mainServerInfo.getRmiServer().campBattleEnd(
                                battleDetail.getBattleDetailType(), battleDetail.getWinTeam() == ConstantFactory.BATTLE_TEAM_1,
                                battleDetail.getTeam1Info(), battleDetail.getTeam2Info().getBaseInfo(), null);

//                        LogUtils.info("singleResult -> " + singleResult);

                        GameServer.getInstance().getActivityCampManager().campBattleResult(campPlayer, singleResult, battleResult, E_ApplyCampActivityType.BATTLE_END);
                    }
                }
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }

        battleResult.setRankCampList(activityManager.getRankCampList());

        return battleResult;
    }

    @Override
    public BattleResultParamCampSingle campBattleEnd(int battleDetailType, boolean win, BattleTemp battleTemp, MatchBaseInfo target, String playerIndex) throws RemoteException {
        //只在游戏主服里处理
        return null;
    }

    @Override
    public void directEndBattle(DirectEndData directEndData) throws RemoteException
    {
        CampPlayer campPlayer = GameServer.getInstance().getActivityCampManager().getPlayer(directEndData.getPlayerIndex());
        if(campPlayer != null)
        {
            //直接结束战斗
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(directEndData.getPlayerServerId());
            if(mainServerInfo != null)
            {
                Player player = mainServerInfo.getRmiServer().getPlayer(directEndData.getPlayerIndex());
                if(player != null)
                {
                    if(directEndData.getBattleDetailType() == E_BattleDetailType.PVE_SPAN_CAMP.getCode())
                    {
                        CampRobotConfig robotConfig = DataFactory.getInstance().getGameObject(DataFactory.CAMP_ROBOT_KEY, Integer.parseInt(directEndData.getTargetIndex()));
                        MatchBaseInfo targetInfo = new MatchBaseInfo(robotConfig, 0);
                        targetInfo.setServerId(directEndData.getPlayerServerId());
                        if(!CoreUtils.isNullOrEmpty(directEndData.getTargetName()))
                            targetInfo.setName(directEndData.getTargetName());

                        BattleResultParamCampSingle result = mainServerInfo.getRmiServer().campBattleEnd(directEndData.getBattleDetailType(), player.fc>targetInfo.getFc(), null, targetInfo, directEndData.getPlayerIndex());
                        LogUtils.info("战斗服务器连接不成功,超时,直接结算结果 PVE -> " + result);
                        GameServer.getInstance().getActivityCampManager().campBattleResult(directEndData.getPlayerIndex(), result, null, E_ApplyCampActivityType.NO_BATTLE);
                    }
                    else if(directEndData.getBattleDetailType() == E_BattleDetailType.PVP_DATA_WORLD_MAP.getCode() || directEndData.getBattleDetailType() == E_BattleDetailType.PVP_SPAN_CAMP.getCode())
                    {
                        MainServerInfo targetPlayerMainServer = GameServer.getInstance().getMainServerInfo(directEndData.getTargetServerId());
                        if(targetPlayerMainServer != null)
                        {
                            Player target = targetPlayerMainServer.getRmiServer().getPlayer(directEndData.getTargetIndex());
                            if(target != null)
                            {
                                MatchBaseInfo baseInfo2 = new MatchBaseInfo(target, directEndData.getTargetServerId());
                                if(!CoreUtils.isNullOrEmpty(directEndData.getTargetName()))
                                    baseInfo2.setName(directEndData.getTargetName());

                                BattleResultParamCampSingle result1 = mainServerInfo.getRmiServer().campBattleEnd(directEndData.getBattleDetailType(), player.fc>baseInfo2.getFc(), null, baseInfo2, player.getObjectIndex());
                                LogUtils.info("战斗服务器连接不成功,超时,直接结算结果 玩家1的结果 -> " + result1);
                                GameServer.getInstance().getActivityCampManager().campBattleResult(player.getObjectIndex(), result1, null, E_ApplyCampActivityType.NO_BATTLE);

                                MatchBaseInfo baseInfo1 = new MatchBaseInfo(player, directEndData.getPlayerServerId());

                                BattleResultParamCampSingle result2 = mainServerInfo.getRmiServer().campBattleEnd(directEndData.getBattleDetailType(), target.fc>baseInfo1.getFc(), null, baseInfo1, target.getObjectIndex());
                                LogUtils.info("战斗服务器连接不成功,超时,直接结算结果 玩家2的结果-> " + result2);
                                GameServer.getInstance().getActivityCampManager().campBattleResult(target.getObjectIndex(), result2, null, E_ApplyCampActivityType.NO_BATTLE);
                            }
                        }
                    }
                }
            }
            else
            {
                LogUtils.error("玩家的主服错误，请检查 -> " + directEndData.getPlayerServerId());
            }
        }

    }


    @Override
    public void updateStatus(String playerIndex, String status) throws RemoteException
    {
        CampPlayer player = GameServer.getInstance().getActivityCampManager().getPlayer(playerIndex);
        if(player != null)
        {
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(player.getPlayerBase().getServerId());
            if(mainServerInfo != null)
                mainServerInfo.getRmiServer().updateStatus(playerIndex, status);
        }
    }

//    @Override
//    public void updateStatusByPlayers(String status, List<String> playerIndexList) throws RemoteException
//    {
//        Map<Integer, List<String>> map = new HashMap<>();
//        CampPlayer player = null;
//        List<String> list = null;
//        for(String index : playerIndexList)
//        {
//            player = GameServer.getInstance().getActivityCampManager().getPlayer(index);
//            if(player != null)
//            {
//                list = map.get(player.getPlayerBase().getServerId());
//                if(list == null)
//                {
//                    list = new ArrayList<>();
//                    map.put(player.getPlayerBase().getServerId(), list);
//                }
//                list.add(index);
//            }
//        }
//
//        MainServerInfo mainServerInfo = null;
//        for(Map.Entry<Integer, List<String>> entry : map.entrySet())
//        {
//            mainServerInfo = GameServer.getInstance().getMainServerInfo(entry.getKey());
//            if(mainServerInfo != null && mainServerInfo.getRmiServer() != null)
//            {
//                mainServerInfo.getRmiServer().updateStatusByPlayers(status, entry.getValue());
//            }
//        }
//    }

    @Override
    public Player getOnlinePlayer(String playerIndex) throws RemoteException
    {
        CampPlayer player = GameServer.getInstance().getActivityCampManager().getPlayer(playerIndex);
//        LogUtils.info("获取到玩家信息 -> " + player);
        if(player != null)
        {
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(player.getPlayerBase().getServerId());
//            LogUtils.info("获取到玩家的主服信息 -> " + mainServerInfo);
            if(mainServerInfo != null)
                return mainServerInfo.getRmiServer().getOnlinePlayer(playerIndex);
            else
            {
                LogUtils.error("阵营战获取在线玩家的ServerInfo为空 -> " + player.getPlayerBase().getName() + " - " + player.getPlayerBase().getServerId());
            }
        }
        else
        {
            LogUtils.error("阵营战获取在线玩家为空 -> playerIndex:" + playerIndex);
        }
        return null;
    }

    @Override
    public Player getOfflinePlayer(String playerIndex) throws RemoteException
    {
        CampPlayer player = GameServer.getInstance().getActivityCampManager().getPlayer(playerIndex);
        if(player != null)
        {
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(player.getPlayerBase().getServerId());
            if(mainServerInfo != null)
                return mainServerInfo.getRmiServer().getOfflinePlayer(playerIndex);
        }
        return null;
    }

    @Override
    public DataFactory getDataFactory() throws RemoteException {
        return DataFactory.getInstance();
    }

    @Override
    public BattleTemp getBattleTemp(int battleType, String playerIndex, String... masterPlayerIndex) throws RemoteException
    {
        CampPlayer campPlayer = GameServer.getInstance().getActivityCampManager().getPlayer(playerIndex);
        if(campPlayer != null)
        {
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(campPlayer.getPlayerBase().getServerId());
            if(mainServerInfo != null && mainServerInfo.getRmiServer() != null)
            {
                return mainServerInfo.getRmiServer().getBattleTemp(battleType, playerIndex);
            }
        }
        return null;
    }

    @Override
    public Player getPlayer(String playerIndex) throws RemoteException
    {
        //活动服向游戏主服获取报名阵营战的人，在活动服里不用实现
        CampPlayer campPlayer = GameServer.getInstance().getActivityCampManager().getPlayer(playerIndex);
        if(campPlayer != null)
        {
            MainServerInfo mainServerInfo = GameServer.getInstance().getMainServerInfo(campPlayer.getPlayerBase().getServerId());
            if(mainServerInfo != null && mainServerInfo.getRmiServer() != null)
            {
                return mainServerInfo.getRmiServer().getPlayer(playerIndex);
            }
        }
        return null;
    }

    @Override
    public boolean checkCampBattle(String playerIndex) throws RemoteException
    {
        return true;
    }

    @Override
    public String test() throws RemoteException {
        return null;
    }

    @Override
    public void battleErrorEnd(List<String> playerIndexList) throws RemoteException {
        Map<Integer, List<String>> map = new HashMap<>();
        CampPlayer player = null;
        List<String> list = null;
        for(String index : playerIndexList)
        {
            player = GameServer.getInstance().getActivityCampManager().getPlayer(index);
            if(player != null)
            {
                list = map.get(player.getPlayerBase().getServerId());
                if(list == null)
                {
                    list = new ArrayList<>();
                    map.put(player.getPlayerBase().getServerId(), list);
                }
                list.add(index);

                GameServer.getInstance().getActivityCampManager().addMatchPlayer(player, E_ApplyCampActivityType.BATTLE_ERROR_END);
            }
        }

        MainServerInfo mainServerInfo = null;
        for(Map.Entry<Integer, List<String>> entry : map.entrySet())
        {
            mainServerInfo = GameServer.getInstance().getMainServerInfo(entry.getKey());
            if(mainServerInfo != null && mainServerInfo.getRmiServer() != null)
            {
                mainServerInfo.getRmiServer().battleErrorEnd(entry.getValue());
            }
        }
    }

    /**
     * 战斗异常结束 比如一直没连接战斗服务器
     * @param errorEndParamList
     * @throws RemoteException
     */
    @Override
    public void mapBattleErrorEnd(List<ErrorEndParam> errorEndParamList) throws RemoteException
    {
       //这里不处理
    }
}
